//
//  CAPOAuthViewController.swift
//  CAPSwift
//
//  Created by captain on 16/4/18.
//  Copyright © 2016年 captain. All rights reserved.
//

import UIKit
import SVProgressHUD
//import CAPAFNetworkingTools
class CAPOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        // MARK: - webView代理
        webView.delegate = self
        
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
  
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    
    // MARK: - 导航栏
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
    }
    
    // MARK: - 点击事件
    @objc private func cancle(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func auto(){
        //js注入
        let jsString = "document.getElementById('userId').value='\(CZWeiboName)';document.getElementById('passwd').value='\(CZWeiboPasswd)'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // MARK: - 懒加载控件webView
    private lazy var webView: UIWebView = UIWebView()
    
    
}
// MARK: - webView代理
extension CAPOAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
//        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
//        SVProgressHUD.dismiss()
    }
    
//    Optional("https://api.weibo.com/oauth2/authorize")
//    Optional("https://api.weibo.com/oauth2/authorize#")
//    Optional("https://api.weibo.com/oauth2/authorize")
//    Optional("http://www.baidu.com/?code=e72e9c37a0a08cc4d7398c91da9ed82e")
//    Optional("https://m.baidu.com/?code=e72e9c37a0a08cc4d7398c91da9ed82e&from=844b&vit=fps")

    // MARK: - 在加载网络的时候调用的方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(REDIRECT_URI){
            //code=e72e9c37a0a08cc4d7398c91da9ed82e"
            
            //判断request请求参数是否存在
            if let q = request.URL?.query{
                
                let code = q.substringFromIndex("code=".endIndex)
//                print(code)
                getUserAccount(code)
            }
        }

        return true
    }
    
    
}

// MARK: - 拓展
extension CAPOAuthViewController {
    // MARK: - 网络请求方法 
    func getUserAccount(code: String){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
//        client_id	true	string	申请应用时分配的AppKey。
//        client_secret	true	string	申请应用时分配的AppSecret。
//        grant_type	true	string	请求的类型，填写authorization_code
//        
//        grant_type为authorization_code时
//        必选	类型及范围	说明
//        code	true	string	调用authorize获得的code值。
//        redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
        let params = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
        ]
        //单例请求
        CAPAFNetworkingTools.shardTools.request(CAPRequestMethod.POST, urlString: urlString, params: params) { (respose, error) -> () in
            //有错误
            if error != nil{
                print(error)
                return
            }
            //请求成功
//            print(respose)
            guard let DataDict = respose as? [String: AnyObject] else{
                print("不是字典")
                return
            }
            //转模型
            let model = CAPOauthModel.init(dict: DataDict)
//            print(model)
            
            self.getUserInfo(model)
            
        }
 
    }
    
    // MARK: - 网络请求，用户信息
    func getUserInfo(model: CAPOauthModel){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
//        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
//        uid	false	int64	需要查询的用户ID。
//        screen_name	false	string	需要查询的用户昵称。
        let params = [
            "access_token":model.access_token!,
            "uid":model.uid!
        ]
        
        CAPAFNetworkingTools.shardTools.request(CAPRequestMethod.GET, urlString: urlString, params: params) { (respose, error) -> () in
            if error != nil {
                print(error)
                return
            }
//            print(respose)
            guard let dataDict = respose as? [String: AnyObject] else{
                print("不是一个字典")
                return
            }
            //是字典
            model.avatar_large = dataDict["avatar_large"] as? String
            model.screen_name = dataDict["screen_name"] as? String
            
            //MARK: - 保存数据
            CAPUserAccountTools.sharedTools.saveUserInfo(model)
            
            //摧毁原来控制器然后跳转
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                //发送通知
                NSNotificationCenter.defaultCenter().postNotificationName(NOTI, object: nil)
            })
            
        }
        
    }
    
    
}




